package cn.com.shopec.erp.multiChannel.service.impl;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import net.sf.json.JSON;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jd.open.api.sdk.DefaultJdClient;
import com.jd.open.api.sdk.JdClient;
import com.jd.open.api.sdk.domain.order.CouponDetail;
import com.jd.open.api.sdk.domain.order.ItemInfo;
import com.jd.open.api.sdk.domain.order.OrderSearchInfo;
import com.jd.open.api.sdk.domain.order.UserInfo;
import com.jd.open.api.sdk.request.order.OrderSearchRequest;
import com.jd.open.api.sdk.response.order.OrderSearchResponse;

import cn.com.shopec.erp.common.constant.SZSCMConstant;
import cn.com.shopec.erp.common.utils.DateUtil;
import cn.com.shopec.erp.common.utils.MD5Util;
import cn.com.shopec.erp.common.utils.StringUtil;
import cn.com.shopec.erp.multiChannel.common.MultiChannelConfig;
import cn.com.shopec.erp.multiChannel.common.MultiChannelConstant;
import cn.com.shopec.erp.multiChannel.common.MultiChannelConvert;
import cn.com.shopec.erp.multiChannel.common.MultiChannelTestData;
import cn.com.shopec.erp.multiChannel.dao.IChannelOrderDao;
import cn.com.shopec.erp.multiChannel.dao.IChannelOrderItemDao;
import cn.com.shopec.erp.multiChannel.dao.IChannelOrderReceiverDao;
import cn.com.shopec.erp.multiChannel.entity.ChannelOrder;
import cn.com.shopec.erp.multiChannel.entity.ChannelOrderItem;
import cn.com.shopec.erp.multiChannel.service.IJingDongService;
import cn.com.shopec.erp.product.commo.BrandVoConvertor;

/**
 * 多渠道Service实现类(京东)
 * @author Administrator
 *
 */
@Service
public class JingDongServiceImpl implements IJingDongService{
	
	private Logger log = Logger.getLogger(JingDongServiceImpl.class);
	
	@Resource
    private IChannelOrderDao channelOrderDao;
	
	@Resource
    private IChannelOrderItemDao channelOrderItemDao;
	
	@Resource
    private IChannelOrderReceiverDao channelOrderReceiverDao;

	/**
	 * 获取京东授权后accessCode的值
	 * @param code 授权登陆后的code
	 * @throws Exception 
	 */
	public boolean getAccessTokenByCode(String code) throws Exception {
		boolean flag=false;
		try {
			StringBuffer url = new StringBuffer();
			url.append(MultiChannelConfig.getString("jd.tokenUrl"));
			url.append("grant_type="+MultiChannelConfig.getString("jd.grantType"));
			url.append("&client_id=" + MultiChannelConfig.getString("jd.appKey"));
			url.append("&client_secret=" + MultiChannelConfig.getString("jd.appSecret"));
			url.append("&scope="+ MultiChannelConfig.getString("jd.scope"));
			url.append("&redirect_uri=" + MultiChannelConfig.getString("jd.redirectUri"));
			url.append("&code=" + code);
			// sb.append("&state=1234");
			log.info("get token url =" + url);
			String jsonText = urlConn(url.toString());
			log.info("jsonText result is = "+jsonText);
			JSONObject obj = JSONObject.fromObject(jsonText);
			log.info("obj result is = "+obj);
			// code
			String resultCode = obj.getString("code");
			log.info("get resultCode = " + resultCode);
			if(MultiChannelConstant.JD_RESULT_CODE.equals(resultCode)) {
				// 授权码
				String accessToken = obj.getString("access_token");
				log.info("jd.accessToken before update：" + MultiChannelConfig.getString("jd.accessToken"));
				MultiChannelConfig.setString("jd.accessToken",accessToken);
				log.info("jd.accessToken after update ：" + MultiChannelConfig.getString("jd.accessToken"));
				log.info(obj.getString("user_nick") + "授权成功.");
				flag=true;
			} else {
				// 授权错误
				log.info("JD getAccessToken fail ：" + jsonText);
			}
		} catch (Exception e) {
			log.info("JD getAccessToken error ：" + e.getMessage());
			e.printStackTrace();
		}
		return flag;
	}

	
	/**
	 * url调用API
	 * @param url
	 * @return
	 * @throws Exception
	 */
	public String urlConn(String url) throws Exception{
		//规范：所有的API请求和响应数据编码皆为GBK格式，URL里的所有参数值请做urlencode编码
		//url=URLEncoder.encode(url,"GBK");
		URL uri = new URL(url);
		HttpURLConnection conn =(HttpURLConnection) uri.openConnection();
		conn.setRequestProperty("Accept-Charset","utf-8");
		conn.setRequestMethod("POST");
		//int cd = conn.getResponseCode();
		InputStream is =conn.getInputStream();
		String jsonText =inputStream2String(is);
		return jsonText;
	}
	
	/**
	 * API签名
	 * 	加密规则
	 * 	① 所有请求参数按照字母先后顺序排列
	 * 	② 把所有参数名和参数值进行拼装
	 *	③ 把appSecret夹在字符串的两端	
	 *	④ 使用MD5进行加密，再转化成大写
	 * @param method
	 * @param paramJsonStr
	 * @return
	 */
	public String md5Sign(String method,String paramJsonStr){
		StringBuffer url = new StringBuffer();
		url.append(MultiChannelConfig.getString("jd.appSecret"));
		url.append("360buy_param_json{"+paramJsonStr+"}");
		url.append("access_token" + MultiChannelConfig.getString("jd.accessToken"));
		url.append("app_key" + MultiChannelConfig.getString("jd.appKey"));
		url.append("method"+method);
		url.append("timestamp" + DateUtil.formatTimesTampDate(new Date()));
		url.append("v" + MultiChannelConfig.getString("jd.v"));
		url.append(MultiChannelConfig.getString("jd.appSecret"));
		return MD5Util.MD5Encode(url.toString(), "").toUpperCase();
	}
	
	/**
	 * 获得接口返回数据
	 * @param method
	 * @param accessToken
	 * @param paramJsonStr
	 * @return
	 * @throws Exception
	 */
	public String getApi(String method,String paramJsonStr) throws Exception{
		StringBuffer url = new StringBuffer();
		url.append(MultiChannelConfig.getString("jd.serverUrl")+"?");
		url.append("360buy_param_json={");
		url.append(paramJsonStr);
		url.append("}&");
		url.append("&access_token=" + MultiChannelConfig.getString("jd.accessToken"));
		url.append("&app_key=" + MultiChannelConfig.getString("jd.appKey"));
		url.append("&method=" + method);
		url.append("&timestamp=" + DateUtil.formatTimesTampDate(new Date()));
		url.append("&v=" + MultiChannelConfig.getString("jd.v"));
		url.append("&sign=" + md5Sign("360buy.order.search",paramJsonStr.toString()));
		
		String jsonText = urlConn(url.toString());
		//JSONObject obj = (JSONObject) JSON.parse(jsonText);
		return jsonText;
	}
	/**
	 * inputStream2String
	 * @param is
	 * @return
	 * @throws IOException
	 */
	private static String inputStream2String(InputStream is) throws IOException{ 
		ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
		int i=-1; 
		while((i=is.read())!=-1){ 
			baos.write(i); 
		} 
		return baos.toString(); 
	}
	/**
	 * 同步京东订单信息
	 * @throws Exception
	 */
	@Transactional
	public String syncJDOrderInfo(String startDate,String endDate) throws Exception{
		String result=SZSCMConstant.SUCCESS;
		try {
			int pageIndex=MultiChannelConstant.PAGE_INDEX;
			int pageSize=MultiChannelConstant.PAGE_SIZE;
			while(true){
				String serverUrl=MultiChannelConfig.getString("jd.serverUrl");
				String accessToken=MultiChannelConfig.getString("jd.accessToken");
				String appKey=MultiChannelConfig.getString("jd.appKey");
				String appSecret=MultiChannelConfig.getString("jd.appSecret");
				JdClient client=new DefaultJdClient(serverUrl,accessToken,appKey,appSecret);
				OrderSearchRequest request=new OrderSearchRequest();
				request.setStartDate(startDate); 									//开始时间
				request.setEndDate(endDate); 										//结束时间
				request.setOrderState(MultiChannelConstant.JD_TRADE_STATE_OUT		//等待出库
								 +","+MultiChannelConstant.JD_TRADE_STATE_WAIT_DELIVERY);  	
				request.setPage(pageIndex+""); 										//查询的页数
				request.setPageSize(pageSize+""); 									//每页的条数（最大page_size 100条）
				request.setOptionalFields(MultiChannelConstant.JD_OPTIONAL_FIELDS); //查询所需字段
				//使用京东云SDK请求获取订单
				OrderSearchResponse response=client.execute(request);
				log.info("OrderSearchResponse result ZhDesc is = "+response.getZhDesc()+",code is = "+response.getCode());
				if(MultiChannelConstant.JD_RESULT_CODE.equals(response.getCode())) {
					// 获得订单数据实体类
					List<OrderSearchInfo> orderInfos = response.getOrderInfoResult().getOrderInfoList(); 
					log.info("response getOrderInfoResult is = "+response.getOrderInfoResult()+",orderInfos result size is = "+orderInfos.size());
					boolean flag=convertAndSaveOrderInfo(orderInfos);
					log.info("convertAndSaveOrderInfo result flag is = "+flag);
					if(!flag){
						result=SZSCMConstant.OPERATION_ERROR;
					}
					//如果返回结果总数大于页数*条数则页数自增，达到自动分页的效果
					if(response.getOrderInfoResult().getOrderTotal()>pageIndex*pageSize){
						pageIndex++;
						log.info("pageIndex is = "+pageIndex);
					}else{
						break;
					}
				}else{
					result=response.getZhDesc();
					break;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		log.info("syncJDOrderInfo result is = "+result);
		return result;
	}
	
	/**
	 * 转换并保存渠道订单信息
	 * @param orderInfos
	 * @return
	 */
	@Override
	@Transactional
	public boolean convertAndSaveOrderInfo(List<OrderSearchInfo> orderInfos){
		boolean flag=false;
		try {
			for (OrderSearchInfo orderInfo : orderInfos) {
				log.info("orderInfo orderId is = "+orderInfo.getOrderId());
				//没有则新增，存在就修改状态
				ChannelOrder order=channelOrderDao.queryByOrderId(orderInfo.getOrderId());
				if(order==null){
					channelOrderDao.save(MultiChannelConvert.convertChannelJDOrder(orderInfo));
					List<ChannelOrderItem> items=MultiChannelConvert.convertChannelJDOrderItem(orderInfo);
					for(int i=0;i<items.size();i++){
						channelOrderItemDao.save(items.get(i));
					}
					channelOrderReceiverDao.save(MultiChannelConvert.convertChannelJDOrderReceiver(orderInfo));
				}else{
					if(!order.getOrderState().equals(MultiChannelConvert.convertOrderState(orderInfo.getOrderState()))){
						order.setOrderState(MultiChannelConvert.convertOrderState(orderInfo.getOrderState()));
						channelOrderDao.update(order);
					}
				}
			}
			flag=true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return flag;
	}
	
	/**
	 * 调用京东发货接口发货
	 * Map 物流信息（物流公司，运单号）
	 */
	public String doJDdelivery(Map<String,String> info){
		return null;
	}
	
}
